#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "cmd.h"

void exec_cmd(struct cmd *cmd)
{
    if (cmd->input)
    {
        int fd = open(cmd->input, O_RDONLY);
        if (fd < 0)
        {
            perror("open");
            exit(EXIT_FAILURE);
        }
        dup2(fd, 0);
        close(fd);
    }
    if (cmd->output)
    {
        int fd = creat(cmd->output, 0666);
        if (fd < 0)
        {
            perror("open");
            exit(EXIT_FAILURE);
        }
        dup2(fd, 1);
        close(fd);
    }
    execvp(cmd->argv[0], cmd->argv);
    perror("execvp");
    exit(EXIT_FAILURE);
}

int builtin_cmd(struct cmd *cmd)
{
    char **argv = cmd->argv;
    if (strcmp(argv[0], "cd") == 0)
    {
        chdir(argv[1]);
        return 1;
    }
    if (strcmp(argv[0], "pwd") == 0)
    {
        char cwd[100];
        getcwd(cwd, sizeof(cwd));
        printf("%s\n", cwd);
        return 1;
    }
    if (strcmp(argv[0], "exit") == 0)
    {
        exit(0);
        return 1;
    }
    return 0;
}

void exec_pipe_cmd(int cmdc, struct cmd *cmdv)
{
    int fds[2];
    if (cmdc == 1)
    {
        exec_cmd(&cmdv[0]);
        return; // return ?
    }
    pipe(fds);
    pid_t pid;
    pid = fork();

    if (pid == 0)
    {
        dup2(fds[1], 1);
        close(fds[0]);
        close(fds[1]);
        exec_pipe_cmd(cmdc - 1, cmdv);
        exit(0);
    }
    wait(NULL);
    dup2(fds[0], 0);
    close(fds[0]);
    close(fds[1]);
    exec_cmd(&cmdv[cmdc - 1]);
}
